import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'nprogress/nprogress.css'

import App from './App.vue'
import router from './router'
import './styles/index.scss'
import { installPermissionDirectives } from './directives/permission'

const app = createApp(App)

// 创建Pinia实例
const pinia = createPinia()

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(pinia)
app.use(router)
app.use(ElementPlus, {
  locale: zhCn,
})

// 注册权限指令
installPermissionDirectives(app)

app.mount('#app')

// 应用初始化和认证状态恢复
import { nextTick } from 'vue'

nextTick(async () => {
  try {
    const { useAuthStore } = await import('@/stores/auth')
    const { usePermissionStore } = await import('@/stores/permission')
    
    // 在应用启动后设置引用
    const authStore = useAuthStore()
    const permissionStore = usePermissionStore()
    permissionStore.setAuthStoreRef(authStore)

    console.log('🔗 已设置authStore引用到permissionStore')
    
    // 如果localStorage中有token，尝试初始化认证状态
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      console.log('🔑 检测到存储的token，正在初始化认证状态...')
      try {
        await authStore.initAuth()
        console.log('✅ 认证状态初始化完成')
      } catch (error) {
        console.warn('⚠️ 认证状态初始化失败:', error)
        // 不需要清除token，让路由守卫处理
      }
    }
  } catch (error) {
    console.error('❌ 应用初始化失败:', error)
  }
})
